package com.cloud.pole.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.util.jwt.JWTInfo;
import com.cloud.pole.common.util.jwt.JwtTokenUtil;

/**
 * Created by ace on 2017/9/12.
 */
public class ClientTokenInterceptor implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(ClientTokenInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
//          Map<String,String> headers = getHeaders(getHttpServletRequest());
//       	logger.debug("headers[" + headers.toString() + "]");
        	JWTInfo jwtInfo = new JWTInfo(CommonConstants.CLIENT_USER_NAME, JWTInfo.USER_TYPE_CLINET, CommonConstants.CLIENT_USER_USER_ID, CommonConstants.CLIENT_NICK_NAME, CommonConstants.CLIENT_REAL_NAME);
        	String clientToken = JwtTokenUtil.generateToken(jwtInfo, CommonConstants.CLIENT_TOKEN_EXPIRE);
        	logger.debug("---------------ClientTokenInterceptor----------------------");
        	logger.debug("clientToken[" + clientToken + "]");
        	logger.debug("-----------------------------------------------------------");
        	requestTemplate.header(CommonConstants.AUTH_CLIENT_TOKEN_HEADER, clientToken);
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
